package cn.biplam.front;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.biplam.common.client.Log;
import cn.biplam.common.client.PageExchange;
import cn.biplam.common.client.Log.Log_Level;
import cn.biplam.common.tools.Call;
import cn.biplam.common.tools.DEBUG;
import cn.biplam.common.wrapper.ErrorMessage;

/**
 * 	显示页面
 * @author 	WangSong
 * @create 	2009-3-20 下午03:27:50
 * @version 1.0
 */
public class Index extends HttpServlet {

	private static final long serialVersionUID = 751400327293775680L;

	/**
	 *  页面显示
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		this.doPost(request, response);
	}

	/**
	 *  页面显示
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		String sPartPath=getPathParam(request);
		String sClassName=PageExchange.get(request, response, sPartPath);
		Call call=null;
		try{
			call=new Call(sClassName,request,response);
		}catch(ErrorMessage e){
			try {
				String url=request.getContextPath()+"/Error.jsp?t="+URLEncoder.encode("【页面错误】", "GB2312");
				url+="&m="+URLEncoder.encode("无效的页面请求:"+sClassName,"GB2312");
				response.sendRedirect(url);
			} catch (IOException e1) {
				DEBUG.println("【系统错误】 URL转码失败"+sClassName);
				e1.printStackTrace();
			}
			return;
		}
		try{ 
			call.run("draw");
		}catch(ErrorMessage e){
			Index.printError(request, response, e);
		}
	} 
	
	/**
	 * 输出错误信息到错误页面
	 * @param request
	 * @param response
	 * @param e
	 */
	public static void printError(HttpServletRequest request, HttpServletResponse response,ErrorMessage e){
		try {
			String url=request.getContextPath()+"/Error.jsp?t="+URLEncoder.encode("错误", "GB2312");
			url+="&m="+URLEncoder.encode("【页面错误】"+
					e.toString().replace('\n', ';').replace(";", "<BR>").replace('\t', ';').replace(";", "&nbsp;&nbsp;&nbsp;&nbsp;")
					,"GB2312");
			Log.write(e,Log_Level.Error);
			response.sendRedirect(url);
		} catch (IOException e1) {
			DEBUG.println("【系统错误】 URL转码失败.");
			e1.printStackTrace();
		}
	}

	/**
	 *  取url参数路径
	 * @param request
	 * @return
	 */
	private String getPathParam(HttpServletRequest request){

		String sRootPath = request.getContextPath();
		String sPath = request.getRequestURI();
		if(sRootPath!=null && sPath!=null && sPath.indexOf(sRootPath)!=-1){
			sPath = sPath.substring(sPath.indexOf(sRootPath)+sRootPath.length()+1,sPath.length());
		}
		sPath=sPath.replace(".bi","");
		return sPath;
	}
}
